/*
 * Validate Binary Search Tree
Given a binary tree, determine if it is a valid binary search tree (BST).

Assume a BST is defined as follows:

The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.
 */
package com.xinpan.exercise;

import java.util.ArrayList;

public class ValidBST {
    public boolean isValidBST(TreeNode root) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if(root == null)
            return true;
        ArrayList<Integer> visit = new ArrayList<Integer>();
        traverse(root.left, visit);
        visit.add(root.val);
        traverse(root.right, visit);
        
        for(int i = 0; i < visit.size()-1; i++)
            if(visit.get(i) >= visit.get(i+1))
                return false;
        return true;
    }
    
    public void traverse(TreeNode root, ArrayList<Integer> visit)
    {
        if(root == null)
            return;
        traverse(root.left, visit);
        visit.add(root.val);
        traverse(root.right, visit);
    }
}
